/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.google.code.pos.dao;

import com.google.code.pos.domain.Item;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jimmy
 */
public class ItemDao {

    private Connection connection;
    private PreparedStatement statement;

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public int saveOrUpdate(Item item) {
        int result = 0;

        if(item.getId() == null) {
            try {
                statement = connection.prepareStatement(
                        "insert into t_mst_item(name, unit, price) values (?, ?, ?)");
                statement.setString(1, item.getName());
                statement.setString(2, item.getUnit());
                statement.setDouble(3, item.getPrice());
                statement.getGeneratedKeys();
                result = statement.executeUpdate();
            } catch (SQLException ex) {
                Logger.getLogger(ItemDao.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            try {
                statement = connection.prepareStatement(
                        "update t_mst_item set name = ?, unit = ?, price = ? where id = ?");
                statement.setString(1, item.getName());
                statement.setString(2, item.getUnit());
                statement.setDouble(3, item.getPrice());
                statement.setLong(4, item.getId());
                result = statement.executeUpdate();
            } catch (SQLException ex) {
                Logger.getLogger(ItemDao.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return result;
    }

    //call a view from database
    public List<Item> findAllItem() {
        List<Item> listItem = new ArrayList<Item>();
        try {
            statement = connection.prepareStatement("select * from v_item");
            ResultSet rs = statement.executeQuery();
            while(rs.next()) {
                Item item = new Item();
                item.setId(rs.getLong("id"));
                item.setName(rs.getString("name"));
                item.setUnit(rs.getString("unit"));
                item.setPrice(rs.getDouble("price"));

                listItem.add(item);
            }
        } catch (SQLException ex) {
            Logger.getLogger(ItemDao.class.getName()).log(Level.SEVERE, null, ex);
        }

        return listItem;
    }

}
